<template>
  <div class="product-edit-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <h2>编辑商品</h2>
      </div>
      <div class="header-right">
        <a-space>
          <a-button @click="handlePreview">
            <template #icon><icon-eye /></template>
            预览
          </a-button>
          <a-button type="primary" @click="handleSave">
            <template #icon><icon-save /></template>
            保存
          </a-button>
        </a-space>
      </div>
    </div>

    <div class="page-content">
      <a-row :gutter="16">
        <!-- 左侧主要内容 -->
        <a-col :span="16">
          <!-- 基本信息 -->
          <a-card class="section-card" title="基本信息">
            <a-form :model="formData" layout="vertical">
              <a-form-item
                field="name"
                label="商品名称"
                :rules="[{ required: true }]"
              >
                <a-input v-model="formData.name" placeholder="请输入商品名称" />
              </a-form-item>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item
                    field="price"
                    label="售价"
                    :rules="[{ required: true }]"
                  >
                    <a-input-number
                      v-model="formData.price"
                      placeholder="请输入售价"
                      :precision="2"
                      :min="0"
                      prefix="¥"
                      style="width: 100%"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="originalPrice" label="原价">
                    <a-input-number
                      v-model="formData.originalPrice"
                      placeholder="请输入原价"
                      :precision="2"
                      :min="0"
                      prefix="¥"
                      style="width: 100%"
                    />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-row :gutter="16">
                <a-col :span="12">
                  <a-form-item
                    field="stock"
                    label="库存"
                    :rules="[{ required: true }]"
                  >
                    <a-input-number
                      v-model="formData.stock"
                      placeholder="请输入库存"
                      :min="0"
                      style="width: 100%"
                    />
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item field="unit" label="单位">
                    <a-input v-model="formData.unit" placeholder="件/个/套" />
                  </a-form-item>
                </a-col>
              </a-row>

              <a-form-item
                field="category"
                label="商品分类"
                :rules="[{ required: true }]"
              >
                <a-tree-select
                  v-model="formData.category"
                  :data="categoryOptions"
                  placeholder="请选择商品分类"
                  allow-clear
                />
              </a-form-item>

              <a-form-item field="tags" label="商品标签">
                <a-select
                  v-model="formData.tags"
                  placeholder="请选择商品标签"
                  allow-create
                  allow-search
                  multiple
                >
                  <a-option v-for="tag in tagOptions" :key="tag" :value="tag">
                    {{ tag }}
                  </a-option>
                </a-select>
              </a-form-item>
            </a-form>
          </a-card>

          <!-- 商品图片 -->
          <a-card class="section-card" title="商品图片">
            <a-upload
              list-type="picture-card"
              :file-list="formData.images"
              :custom-request="handleUpload"
              @remove="handleRemoveImage"
              multiple
            >
              <template #upload-button>
                <div class="upload-button">
                  <icon-plus />
                  <div class="upload-text">上传图片</div>
                </div>
              </template>
            </a-upload>
            <div class="upload-tips">
              <p>提示：</p>
              <p>1. 第一张图片将作为商品主图</p>
              <p>2. 建议尺寸：800x800px</p>
              <p>3. 支持jpg、png格式</p>
            </div>
          </a-card>

          <!-- 商品详情 -->
          <a-card class="section-card" title="商品详情">
            <div class="rich-editor">
              <a-textarea
                v-model="formData.description"
                :auto-size="{ minRows: 10, maxRows: 20 }"
                placeholder="请输入商品详情描述"
              />
            </div>
          </a-card>
        </a-col>

        <!-- 右侧边栏 -->
        <a-col :span="8">
          <!-- 商品规格 -->
          <a-card class="section-card" title="商品规格">
            <div class="spec-header">
              <a-radio-group v-model="formData.specType" type="button">
                <a-radio value="single">单规格</a-radio>
                <a-radio value="multiple">多规格</a-radio>
              </a-radio-group>
            </div>

            <!-- 单规格 -->
            <template v-if="formData.specType === 'single'">
              <div class="single-spec">
                <p class="spec-tip">使用统一规格</p>
              </div>
            </template>

            <!-- 多规格 -->
            <template v-else>
              <div class="multi-spec">
                <div
                  v-for="(spec, index) in formData.specs"
                  :key="index"
                  class="spec-item"
                >
                  <div class="spec-name">
                    <a-input
                      v-model="spec.name"
                      placeholder="规格名"
                      style="width: 120px"
                    />
                  </div>
                  <div class="spec-values">
                    <a-input-tag
                      v-model="spec.values"
                      placeholder="输入规格值后回车"
                      allow-clear
                    />
                  </div>
                  <div class="spec-actions">
                    <a-button
                      type="text"
                      status="danger"
                      @click="removeSpec(index)"
                    >
                      <template #icon><icon-delete /></template>
                    </a-button>
                  </div>
                </div>
                <div class="add-spec">
                  <a-button type="dashed" long @click="addSpec">
                    <template #icon><icon-plus /></template>
                    添加规格项
                  </a-button>
                </div>
              </div>

              <!-- 规格组合 -->
              <div v-if="specCombinations.length" class="spec-combinations">
                <a-table
                  :columns="specColumns"
                  :data="specCombinations"
                  :pagination="false"
                >
                  <template #price="{ record }">
                    <a-input-number
                      v-model="record.price"
                      :precision="2"
                      :min="0"
                      prefix="¥"
                      style="width: 120px"
                    />
                  </template>
                  <template #stock="{ record }">
                    <a-input-number
                      v-model="record.stock"
                      :min="0"
                      style="width: 100px"
                    />
                  </template>
                </a-table>
              </div>
            </template>
          </a-card>

          <!-- 销售设置 -->
          <a-card class="section-card" title="销售设置">
            <a-form :model="formData" layout="vertical">
              <a-form-item field="status" label="商品状态">
                <a-radio-group v-model="formData.status">
                  <a-radio value="on">上架</a-radio>
                  <a-radio value="off">下架</a-radio>
                </a-radio-group>
              </a-form-item>

              <a-form-item field="limitBuy" label="限购数量">
                <a-input-number
                  v-model="formData.limitBuy"
                  placeholder="0表示不限购"
                  :min="0"
                  style="width: 100%"
                />
              </a-form-item>

              <a-form-item field="sort" label="商品排序">
                <a-input-number
                  v-model="formData.sort"
                  placeholder="数值越小越靠前"
                  :min="0"
                  style="width: 100%"
                />
              </a-form-item>
            </a-form>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 预览弹窗 -->
    <a-modal
      v-model:visible="previewVisible"
      title="商品预览"
      :footer="false"
      width="800px"
    >
      <div class="preview-content">
        <div class="preview-header">
          <h3>{{ formData.name || "商品名称" }}</h3>
          <div class="preview-price">
            <span class="current-price">¥{{ formData.price || "0.00" }}</span>
            <span v-if="formData.originalPrice" class="original-price">
              ¥{{ formData.originalPrice }}
            </span>
          </div>
        </div>
        <div class="preview-info">
          <div class="info-item">
            <span class="label">库存：</span>
            <span class="value"
              >{{ formData.stock || 0 }}{{ formData.unit }}</span
            >
          </div>
          <div class="info-item">
            <span class="label">分类：</span>
            <span class="value">{{ getCategoryName(formData.category) }}</span>
          </div>
          <div v-if="formData.tags?.length" class="info-item">
            <span class="label">标签：</span>
            <span class="value">
              <a-tag
                v-for="tag in formData.tags"
                :key="tag"
                color="blue"
                size="small"
              >
                {{ tag }}
              </a-tag>
            </span>
          </div>
        </div>
        <div v-if="formData.images?.length" class="preview-images">
          <a-carousel :auto-play="true">
            <a-carousel-item
              v-for="(image, index) in formData.images"
              :key="index"
            >
              <img :src="image.url" :alt="formData.name" />
            </a-carousel-item>
          </a-carousel>
        </div>
        <div class="preview-description">
          <h4>商品详情</h4>
          <div class="description-content">
            {{ formData.description || "暂无详情" }}
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from "vue";
import { Message } from "@arco-design/web-vue";
import {
  IconSave,
  IconEye,
  IconPlus,
  IconDelete,
} from "@arco-design/web-vue/es/icon";

// 表单数据
const formData = reactive({
  name: "",
  price: null,
  originalPrice: null,
  stock: null,
  unit: "件",
  category: null,
  tags: [],
  images: [],
  description: "",
  specType: "single",
  specs: [],
  status: "off",
  limitBuy: 0,
  sort: 0,
});

// 分类选项
const categoryOptions = [
  {
    key: "1",
    title: "景点门票",
    children: [
      { key: "1-1", title: "景区门票" },
      { key: "1-2", title: "演出门票" },
    ],
  },
  {
    key: "2",
    title: "文创商品",
    children: [
      { key: "2-1", title: "手工艺品" },
      { key: "2-2", title: "纪念品" },
    ],
  },
];

// 标签选项
const tagOptions = ["热门", "新品", "推荐", "限时", "特惠"];

// 规格相关
const specColumns = [
  { title: "规格", dataIndex: "specs" },
  {
    title: "价格",
    slotName: "price",
  },
  {
    title: "库存",
    slotName: "stock",
  },
];

// 计算规格组合
const specCombinations = computed(() => {
  if (formData.specType !== "multiple" || !formData.specs.length) {
    return [];
  }

  const combinations = [];
  const specs = formData.specs.filter(
    (spec) => spec.name && spec.values.length,
  );

  if (!specs.length) {
    return [];
  }

  const generateCombinations = (current, specs, index) => {
    if (index === specs.length) {
      combinations.push({
        specs: current.join(" + "),
        price: formData.price,
        stock: Math.floor(formData.stock / combinations.length) || 0,
      });
      return;
    }

    const currentSpec = specs[index];
    currentSpec.values.forEach((value) => {
      generateCombinations([...current, value], specs, index + 1);
    });
  };

  generateCombinations([], specs, 0);
  return combinations;
});

// 添加规格
const addSpec = () => {
  formData.specs.push({
    name: "",
    values: [],
  });
};

// 删除规格
const removeSpec = (index) => {
  formData.specs.splice(index, 1);
};

// 获取分类名称
const getCategoryName = (key) => {
  if (!key) return "";

  const findCategory = (options) => {
    for (const option of options) {
      if (option.key === key) {
        return option.title;
      }
      if (option.children) {
        const found = findCategory(option.children);
        if (found) return found;
      }
    }
    return "";
  };

  return findCategory(categoryOptions);
};

// 处理图片上传
const handleUpload = async ({ file, onSuccess, onError }) => {
  try {
    // 模拟上传
    await new Promise((resolve) => setTimeout(resolve, 1000));
    const url = URL.createObjectURL(file);
    formData.images.push({
      uid: Date.now(),
      name: file.name,
      url,
    });
    onSuccess();
  } catch (error) {
    onError();
  }
};

// 处理图片删除
const handleRemoveImage = (file) => {
  const index = formData.images.findIndex((item) => item.uid === file.uid);
  if (index > -1) {
    formData.images.splice(index, 1);
  }
};

// 预览相关
const previewVisible = ref(false);
const handlePreview = () => {
  previewVisible.value = true;
};

// 保存
const handleSave = async () => {
  try {
    // TODO: 调用保存API
    await new Promise((resolve) => setTimeout(resolve, 1000));
    Message.success("保存成功");
  } catch (error) {
    Message.error("保存失败");
  }
};
</script>

<style lang="scss" scoped>
.product-edit-page {
  .page-header {
    @apply flex items-center justify-between mb-6;

    h2 {
      @apply text-xl font-medium;
    }
  }

  .page-content {
    .section-card {
      @apply mb-6;

      .upload-button {
        @apply flex flex-col items-center justify-center;
        height: 100%;

        .upload-text {
          @apply mt-2 text-sm text-gray-500;
        }
      }

      .upload-tips {
        @apply mt-4 p-4 bg-gray-50 rounded-lg text-sm text-gray-600 space-y-1;
      }

      .rich-editor {
        @apply border border-gray-300 rounded-lg p-4;
      }

      .spec-header {
        @apply mb-4;
      }

      .single-spec {
        @apply py-4 text-center text-gray-500;
      }

      .multi-spec {
        .spec-item {
          @apply flex items-center gap-4 mb-4;
        }

        .add-spec {
          @apply mt-4;
        }
      }

      .spec-combinations {
        @apply mt-6 border-t pt-4;
      }
    }
  }
}

// 预览样式
.preview-content {
  .preview-header {
    @apply mb-6;

    h3 {
      @apply text-xl font-medium mb-4;
    }

    .preview-price {
      .current-price {
        @apply text-2xl text-red-500 font-medium;
      }

      .original-price {
        @apply ml-2 text-sm text-gray-400 line-through;
      }
    }
  }

  .preview-info {
    @apply mb-6;

    .info-item {
      @apply flex items-center mb-2;

      .label {
        @apply text-gray-500 w-16;
      }

      .value {
        @apply flex-1;
      }
    }
  }

  .preview-images {
    @apply mb-6;

    :deep(.arco-carousel) {
      @apply rounded-lg overflow-hidden;
    }

    img {
      @apply w-full h-full object-cover;
      height: 400px;
    }
  }

  .preview-description {
    h4 {
      @apply text-lg font-medium mb-4;
    }

    .description-content {
      @apply text-gray-600 whitespace-pre-wrap;
    }
  }
}
</style>
